package com.graduation.springbootinit.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.graduation.springbootinit.common.BaseResponse;
import com.graduation.springbootinit.common.ErrorCode;
import com.graduation.springbootinit.common.ResultUtils;
import com.graduation.springbootinit.exception.BusinessException;
import com.graduation.springbootinit.model.entity.ShopPart.MonthlyStoreSales;
import com.graduation.springbootinit.model.entity.ShopPart.Store;
import com.graduation.springbootinit.service.MonthlyStoreSalesService;
import com.graduation.springbootinit.service.StoreService;
import org.springframework.web.bind.annotation.*;
import lombok.Data;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/store")
public class StoreController {

    @Resource
    private MonthlyStoreSalesService monthlyStoreSalesService;

    @Resource
    private StoreService storeService;

    /**
     * 当前商铺的Session键
     */
    private static final String CURRENT_STORE_STATE = "current_store_state";

    /**
     * 用户ID请求参数
     */
    @Data
    public static class UserIdRequest {
        private Long userId;
    }

    /**
     * 商铺ID请求参数
     */
    @Data
    public static class StoreIdRequest {
        private Long storeId;
    }

    /**
     * 统计并更新指定年月的商铺销售数据
     */
    @PostMapping("/monthly-sales/calculate")
    public BaseResponse<Void> calculateMonthlySales(@RequestParam Integer year, @RequestParam Integer month) {
        if (year == null || month == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (month < 1 || month > 12) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "月份必须在1-12之间");
        }
        monthlyStoreSalesService.calculateAndUpdateMonthlySales(year, month);
        return ResultUtils.success(null);
    }

    /**
     * 获取指定年月的所有商铺销售数据
     */
    @GetMapping("/monthly-sales/list")
    public BaseResponse<List<MonthlyStoreSales>> getMonthlyStoreSales(@RequestParam Integer year, @RequestParam Integer month) {
        if (year == null || month == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (month < 1 || month > 12) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "月份必须在1-12之间");
        }
        return monthlyStoreSalesService.getMonthlyStoreSales(year, month);
    }

    /**
     * 获取指定商铺的销售历史数据（分页）
     */
    @GetMapping("/monthly-sales/history")
    public BaseResponse<Page<MonthlyStoreSales>> getStoreSalesHistory(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,HttpServletRequest request) {
        Long storeId = (Long) request.getSession().getAttribute(CURRENT_STORE_STATE);

        if (storeId == null || storeId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize < 1) {
            pageSize = 10;
        }
        return monthlyStoreSalesService.getStoreSalesHistory(storeId, pageNum, pageSize);
    }

    /**
     * 获取指定年月的平台总销售额
     */
    @GetMapping("/monthly-sales/total")
    public BaseResponse<BigDecimal> getTotalSalesByMonth(@RequestParam Integer year, @RequestParam Integer month) {
        if (year == null || month == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (month < 1 || month > 12) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "月份必须在1-12之间");
        }
        return monthlyStoreSalesService.getTotalSalesByMonth(year, month);
    }

    /**
     * 获取指定年份的月度销售数据
     */
    @GetMapping("/monthly-sales/yearly")
    public BaseResponse<List<MonthlyStoreSales>> getYearlyStoreSales(@RequestParam Integer year) {
        if (year == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return monthlyStoreSalesService.getYearlyStoreSales(year);
    }

    /**
     * 获取指定商铺在指定年月的销售数据
     */
    @GetMapping("/monthly-sales/store")
    public BaseResponse<MonthlyStoreSales> getStoreMonthlySales(
            @RequestParam Integer year,
            @RequestParam Integer month,HttpServletRequest request) {
        Long storeId = (Long) request.getSession().getAttribute(CURRENT_STORE_STATE);
        if (storeId == null || storeId <= 0 || year == null || month == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (month < 1 || month > 12) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "月份必须在1-12之间");
        }
        return monthlyStoreSalesService.getStoreMonthlySales(storeId, year, month);
    }

    /**
     * 获取商铺指定年份的月度销售数据列表
     */
    @GetMapping("/yearly-sales/store")
    public BaseResponse<List<MonthlyStoreSales>> getStoreYearlySales(
            @RequestParam Integer year,
            HttpServletRequest request) {
        Long storeId = (Long) request.getSession().getAttribute(CURRENT_STORE_STATE);
        if (storeId == null || storeId <= 0 || year == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 获取当前时间
        LocalDate now = LocalDate.now();
        int currentYear = now.getYear();
        int currentMonth = now.getMonthValue();

        // 计算最大月份
        int maxMonth = 12;
        if (year == currentYear) {
            // 如果是当前年份，则只统计到当前月份的上个月
            maxMonth = currentMonth - 1;
            // 如果是当年1月，没有上个月的数据
            if (maxMonth < 1) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "当前年份暂无销售数据");
            }
        } else if (year > currentYear) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "不能查询未来的销售数据");
        }

        List<MonthlyStoreSales> monthlyStoreSalesList = new ArrayList<>();
        for (int month = 1; month <= maxMonth; month++) {
            BaseResponse<MonthlyStoreSales> response = monthlyStoreSalesService.getStoreMonthlySales(storeId, year, month);
            if (response.getData() != null) {
                monthlyStoreSalesList.add(response.getData());
            }
        }

        return ResultUtils.success(monthlyStoreSalesList);
    }

    /**
     * 根据商铺ID获取商铺详细信息
     */
    @PostMapping("/info")
    public BaseResponse<Store> getStoreInfo(@RequestBody StoreIdRequest storeIdRequest) {
        if (storeIdRequest == null || storeIdRequest.getStoreId() == null || storeIdRequest.getStoreId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "商铺ID不合法");
        }
        Store store = storeService.getStoreById(storeIdRequest.getStoreId());
        if (store == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "商铺不存在");
        }
        return ResultUtils.success(store);
    }

    /**
     * 根据商铺ID获取商铺名称
     */
    @GetMapping("/name/{id}")
    public BaseResponse<String> getStoreName(@PathVariable Long id) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String storeName = storeService.getStoreNameById(id);
        if (storeName == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "商铺不存在");
        }
        return ResultUtils.success(storeName);
    }

    /**
     * 根据用户ID获取该用户的所有商铺信息
     */
    @PostMapping("/user/stores")
    public BaseResponse<List<Store>> getStoresByUserId(@RequestBody UserIdRequest userIdRequest) {
        if (userIdRequest == null || userIdRequest.getUserId() == null || userIdRequest.getUserId() < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户ID不合法");
        }
        List<Store> stores = storeService.getStoresByUserId(userIdRequest.getUserId());
        return ResultUtils.success(stores);
    }

    /**
     * 切换当前管理的商铺
     */
    @PostMapping("/switch")
    public BaseResponse<Store> switchCurrentStore(@RequestBody StoreIdRequest storeIdRequest, HttpServletRequest request) {
        if (storeIdRequest == null || storeIdRequest.getStoreId() == null || storeIdRequest.getStoreId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "商铺ID不合法");
        }
        
        // 验证商铺是否存在且属于当前用户
        Store store = storeService.verifyStoreOwnership(storeIdRequest.getStoreId(), request);
        
        // 将当前选中的商铺ID存入Session
        request.getSession().setAttribute(CURRENT_STORE_STATE, storeIdRequest.getStoreId());
        
        return ResultUtils.success(store);
    }

    /**
     * 获取当前管理的商铺信息
     */
    @GetMapping("/current")
    public BaseResponse<Store> getCurrentStore(HttpServletRequest request) {
        // 从Session中获取当前商铺ID
        Object storeId = request.getSession().getAttribute(CURRENT_STORE_STATE);
        if (storeId == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "未选择当前商铺");
        }
        
        // 获取商铺信息
        Store store = storeService.verifyStoreOwnership((Long) storeId, request);
        return ResultUtils.success(store);
    }
}